import React, { Component, createContext, createRef } from 'react';

const { Provider, Consumer } = createContext()

// 属性：外来的
// 状态：代表的是自己的

class Son extends Component {
  componentDidMount() {
    console.log(4)
  }
  render() {
    return (
      <Consumer>
        {
          (data) => {
            return <div>
              {/* 孙子{data.name} */}
              <button onClick={() => data.setName('孙子')}>修改爷爷的name</button>
            </div>
          }
        }
      </Consumer>
    )
  }
}

class Child extends Component {
  constructor(props) {
    super(props)
    this.audioDom = createRef()
    this.iptDom = createRef()
    this.sonDom = createRef()
    this.state = {
      username: "2004"
    }
  }
  play() {
    console.log('ref', this.iptDom.current.value)
  }
  render() {
    return (
      <div>我是子组件
        {/* <div>{this.props.pName}</div> */}
        <Son ref={this.sonDom}></Son>
        <audio ref={this.audioDom} src="./test.mp3" controls="control"></audio>
        <input ref={this.iptDom}></input>
        <div>
          <label>用户名</label>
          <input value={this.state.username} onChange={e => this.setState({
            username: e.target.value
          })}></input>
        </div>
        受控组件的值:
        {
          this.state.username
        }
        <button onClick={() => this.play()}>获取ref</button>
        <button onClick={() => this.props.pSetName('hello2')}>点击触发父组件的函数</button>
      </div>
    )
  }
}

class Parent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      name: '2004A'
    }
    this.setName = this.setName.bind(this)
  }
  setName(str) {
    if(str === '孙子') {
      console.log('不让你改')
    } else {
      this.setState({
        name: str
      })
    }
  }
  shouldComponentUpdate(nextProps, nextState) {
    if(nextState.name === 'hello') {
      return true
    } else {
      return false
    }
  }
  render() {
    // 返回一个虚拟dom
    return (
      <Provider value={{name: this.state.name, age: '18', setName: this.setName}}>
        <div>
          我是父组件
          { this.state.name }
          <Child pName={this.state.name} pSetName={this.setName}></Child>
          {/* vue的写法 */}
          {/* <Child v-bind:pName="name"></Child> */}
          
        </div>
      </Provider>
      
    )
  }
}

export default Parent;
